package com.hunter.jerrymouse.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by hunter
 * <p>
 * spring工具类
 */
public class SpringBeanUtils {

    /**
     * 默认的配置文件路径
     */
    private static final String DEFAULT_CONFIG_FILE_PATH = "classpath:application-context.xml";

    /**
     * spring context
     */
    private static ApplicationContext APPLICATION_CONTEXT;

    /**
     * 获取 ApplicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }

    /**
     * 加载spring
     *
     * @return
     */
    public static ApplicationContext doLoad() {
        return doLoad(DEFAULT_CONFIG_FILE_PATH);
    }

    /**
     * 加载spring
     *
     * @param configFilePath
     * @return
     */
    public static ApplicationContext doLoad(String configFilePath) {
        if (APPLICATION_CONTEXT == null) {
            APPLICATION_CONTEXT = new ClassPathXmlApplicationContext(configFilePath);
        }
        return APPLICATION_CONTEXT;
    }

    /**
     * 根据名称获取bean
     *
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName) {
        if (isLoaded()) {
            return (T) APPLICATION_CONTEXT.getBean(beanName);
        }

        return null;
    }

    /**
     * 根据类型获取bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (isLoaded()) {
            return APPLICATION_CONTEXT.getBean(clazz);
        }

        return null;
    }

    /**
     * 简单的校验方法
     *
     * @return
     */
    private static boolean isLoaded() {
        return APPLICATION_CONTEXT != null;
    }
}
